﻿using BattleBotsMattAndSunny.Components.Interfaces;
using BattleBotsMattAndSunny.Extensions;
using BattleBotsMattAndSunny.Model;
using Robocode;
using Robocode.Util;

namespace BattleBotsMattAndSunny.Components.Radar
{
    public class LockingRadar : IRadarManager
    {
        public AdvancedRobot robot { get; set; }

        public IDataManager dataManager { get; set; }

        public Enemy CurrentTarget { get; set; }

        public LockingRadar(IDataManager dm, AdvancedRobot r)
        {
            robot = r;
            dataManager = dm;
        }

        //todo add to abstract method?
        public void Scan(ScannedRobotEvent e)
        {
            double radarTurn =
                // Absolute bearing to target
       robot.HeadingRadians + e.BearingRadians
                // Subtract current radar heading to get turn required
       - robot.RadarHeadingRadians;

            robot.SetTurnRadarRightRadians(Utils.NormalRelativeAngle(radarTurn));

            dataManager.StoreScan(e);
            var existingEnemy = dataManager.GetEnemy(e.Name);
            if (existingEnemy == null)
            {
                var newEnemy = new Enemy(e, robot);
                dataManager.StoreEnemy(newEnemy);
            }
            else
            {
                existingEnemy.UpdateEnemy(e, robot);
            }
            //Focus on scanned enemy if it is closer
            if (CurrentTarget == null || CurrentTarget.Distance > e.Distance)
            {
                CurrentTarget = dataManager.GetEnemy(e.Name);
            }
        }

        public void Move()
        {
            robot.TurnRadarRightRadians(double.PositiveInfinity);
        }
    }
}